// 接口返回结构
interface ListOptionsRes<T> {
  code: number;
  data?: any;
  msg: string;
  rows: T[];
  total: number;
}

// 分页参数
interface Options {
  pageNum?: number
  pageSize?: number
};

// 列表请求接口
type ListService<R> = (params: Options) => Promise<ListOptionsRes<R>>

// 加载状态
type Status = 'more' | 'loading' | 'nomore';

export function usePageList<T>(service: ListService<T>, options: Options = {}) {
  const pageNum = ref(options.pageNum ?? 1);
  const pageSize = ref(options.pageSize ?? 10);
  const status = ref<Status>('loading');
  
  const list: Ref<T[]> = ref([]);
  const total = ref(0);

  const getList = async () => {
    try {
      status.value = 'loading';
      const res = await service({ pageNum: unref(pageNum), pageSize: unref(pageSize) });
      total.value = res.total;
      
      if(unref(pageNum) === 1){
        list.value = [...res.rows];
      }else if(unref(list).length < unref(total) ){
        list.value.push(...res.rows);
      }
      status.value = unref(list).length >= unref(total) ? 'nomore' : 'more';
      pageNum.value = unref(list).length >= unref(total) ? pageNum.value : pageNum.value + 1; // 加载完毕自增一页,下次加载下一页
    } catch (error) {
      status.value = 'more'
    }
  };

  const search = async () => {
    pageNum.value = options.pageNum ?? 1;
    await getList();
  };

  return {
    pageNum,
    pageSize,
    getList,
    list,
    search,
    status
  }
}